package com.qfjy.project.oauth;

import com.qfjy.entity.User;
import com.qfjy.entity.Weiuser;
import com.qfjy.project.weixin.api.userinfo.UserInfoUtil;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.UserService;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@RequestMapping("weixin")
@Controller
public class WeiXinOauth {
    @Autowired
    private UserService userService;
    @Autowired
    private WeiUserService weiUserService;
    @Autowired
    private UserInfoUtil userInfoUtil;

    //1.用户是否同意授权


    /**
     * http://hucaiyuan123.natapp1.cc/weixin/oauth
     */
    @RequestMapping("oauth")

    public void oauth(HttpServletResponse response) throws IOException {
        String path = "http://hucaiyuan123.natapp1.cc/weixin/oauthInvoke";
        path = URLEncoder.encode(path, "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId +
                "&redirect_uri=" + path +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2007" +
                "#wechat_redirect";
        response.sendRedirect(url);
    }

    //如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE。
    //http://hucaiyuan123.natapp1.cc/weixin/oauthInvoke?code=CODE&state=STATE
    @ResponseBody
    @RequestMapping("oauthInvoke")
    public String oauthInvoke(HttpServletRequest request) {
        //得到code
        String code = request.getParameter("code");
        log.info("用户同意授权后code数据:" + code);
        String state = request.getParameter("state");
        log.info("用户开发自定义数据传输：" + state);
        //C通过code向微信服务器认证资源获取access_token
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + MenuManager.appId +
                "&secret=" + MenuManager.appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        //D 发送请求获取access_token
        JSONObject jsonObject = WeixinUtil.httpRequest(path, "POST", null);
        log.info("请求微信服务器得到access_token：" + jsonObject.toString());

        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //E 通过access_token获取资源服务器信息  F返回资源服务器信息  https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        String userInfoUrl = "ttps://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + access_token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject jsonObject1 = WeixinUtil.httpRequest(userInfoUrl, "GET", null);
        return jsonObject1.toString();

    }

    /**
     * 个人中心   http://hucaiyuan123.natapp1.cc/weixin/oauthUser
     */
    @RequestMapping("oauthUser")
    public void oauthUser(HttpServletResponse response) throws IOException {
        String path = "http://hucaiyuan123.natapp1.cc/weixin/oauthUserInvoke";
        path = URLEncoder.encode(path, "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId +
                "&redirect_uri=" + path +
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state=java2007" +
                "#wechat_redirect";
        response.sendRedirect(url);
    }

    @RequestMapping("oauthUserInvoke")
    public String oauthUserInvoke(HttpServletRequest request) {
        //得到code
        String code = request.getParameter("code");
        log.info("用户同意授权后code数据:" + code);
        String state = request.getParameter("state");
        log.info("用户开发自定义数据传输：" + state);
        //C通过code向微信服务器认证资源获取access_token
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + MenuManager.appId +
                "&secret=" + MenuManager.appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        //D 发送请求获取access_token
        JSONObject jsonObject = WeixinUtil.httpRequest(path, "POST", null);
        log.info("请求微信服务器得到access_token：" + jsonObject.toString());

        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        Weiuser weiuser = weiUserService.selectWeiUserByOpenid(openid);
        if (weiuser == null) {
            log.error("-----用收集到该用户的个人信息");
            userInfoUtil.userInfoService(openid);
        } else {
            //

            User user = userService.selectUserByWid(weiuser.getId());
            if (user == null) {
                request.setAttribute("wid", weiuser.getId());

                return "pages/user/login";
            } else {
                request.setAttribute("user", user);
                return "pages/user/userInfo";
            }
        }
        return "oauth";

    }

    //会议的发布
    @RequestMapping("oauthMeetingPub")
    public void oauthMeetingPub(HttpServletResponse response) throws IOException {
        String path = "http://hucaiyuan123.natapp1.cc/weixin/oauthMeetingPubInvoke";
        path = URLEncoder.encode(path, "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId +
                "&redirect_uri=" + path +
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state=java2007" +
                "#wechat_redirect";
        response.sendRedirect(url);
    }

    @RequestMapping("oauthMeetingPubInvoke")
    public String oauthMeetingPubInvoke(HttpServletRequest request) {
        //得到code
        String code = request.getParameter("code");
        log.info("用户同意授权后code数据:" + code);
        String state = request.getParameter("state");
        log.info("用户开发自定义数据传输：" + state);
        //C通过code向微信服务器认证资源获取access_token
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + MenuManager.appId +
                "&secret=" + MenuManager.appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        //D 发送请求获取access_token
        JSONObject jsonObject = WeixinUtil.httpRequest(path, "POST", null);
        log.info("请求微信服务器得到access_token：" + jsonObject.toString());

        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        Weiuser weiuser = weiUserService.selectWeiUserByOpenid(openid);
        if (weiuser == null) {
            log.error("-----用收集到该用户的个人信息");
            userInfoUtil.userInfoService(openid);
        } else {
            //

            User user = userService.selectUserByWid(weiuser.getId());
            if (user.getRid() == 1) {
                request.setAttribute("uid", user.getId());
                return "pages/meetingpub/meetingpubAdd";
            } else if (user.getRid() == 0) {
                return "pages/unauth";
            } else {
                log.error("查看组权限---》");

            }
        }
        return "oauth";

    }

}